const { app, BrowserWindow, ipcMain, Notification, powerSaveBlocker, screen } = require('electron')
const path = require('path')
const { createTray } = require('./tray')

let mainWindow
let alertWindow = null
let powerBlockerId = null

// 确保应用单实例运行
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, '../public/icon.png')
  })

  // 开发环境加载本地服务，生产环境加载静态文件
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:3000')
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // 创建系统托盘
  createTray(mainWindow)
}

// 创建提醒窗口
function createAlertWindow(alertData) {
  // 如果已有提醒窗口则关闭
  if (alertWindow) {
    alertWindow.close()
  }

  // 阻止系统休眠
  if (powerBlockerId === null) {
    powerBlockerId = powerSaveBlocker.start('prevent-display-sleep')
  }

  // 获取屏幕尺寸
  const primaryDisplay = screen.getPrimaryDisplay()
  const { width, height } = primaryDisplay.workAreaSize

  // 创建置顶的提醒窗口
  alertWindow = new BrowserWindow({
    width: 400,
    height: 300,
    x: width - 420,
    y: height - 320,
    alwaysOnTop: true,
    frame: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, '../public/icon.png')
  })

  // 加载提醒页面
  if (process.env.NODE_ENV === 'development') {
    alertWindow.loadURL(`http://localhost:3000/#/alert?id=${alertData.id}`)
  } else {
    alertWindow.loadFile(path.join(__dirname, '../dist/index.html'), {
      hash: `/alert?id=${alertData.id}`
    })
  }

  // 触发系统通知
  if (Notification.isSupported()) {
    new Notification({
      title: alertData.title,
      body: alertData.content,
      icon: path.join(__dirname, '../public/icon.png')
    }).show()
  }

  alertWindow.on('closed', () => {
    alertWindow = null
    // 允许系统休眠
    if (powerBlockerId !== null) {
      powerSaveBlocker.stop(powerBlockerId)
      powerBlockerId = null
    }
  })

  return alertWindow
}

// 监听来自渲染进程的事件
ipcMain.on('show-alert', (event, alertData) => {
  createAlertWindow(alertData)
})

ipcMain.on('close-alert', (event, alertId) => {
  if (alertWindow) {
    alertWindow.close()
  }
  // 通知所有窗口关闭特定提醒
  if (mainWindow) {
    mainWindow.webContents.send('alert-closed', alertId)
  }
})

ipcMain.on('heartbeat-status', (event, status) => {
  if (mainWindow) {
    mainWindow.webContents.send('heartbeat-status', status)
  }
})

// 应用生命周期事件
app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
